package com.wngbms.grpc.demo;

import com.wngbms.grpc.hello.HelloReq;
import com.wngbms.grpc.hello.HelloResp;
import com.wngbms.grpc.hello.HelloServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class DemoServer extends HelloServiceGrpc.HelloServiceImplBase {

    private Server server;

    @Override
    public void say(HelloReq request, StreamObserver<HelloResp> responseObserver) {
        HelloResp resp = HelloResp.newBuilder().setMessage("hello Time I love apple").build();
        responseObserver.onNext(resp);
        responseObserver.onCompleted();
        log.info("req:{}", request.getName());
    }

    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public void start() throws IOException {
        server = ServerBuilder
                .forPort(8090).addService(new DemoServer()).build().start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            DemoServer.this.stop();
        }));
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        DemoServer demoServer = new DemoServer();
        demoServer.start();
        demoServer.blockUntilShutdown();
    }

}
